package com.longtop.framework.orm.database;

import com.longtop.framework.orm.IDialect;

public class SQLServer2005Dialect implements IDialect {
	public String getPagedString(String sql, boolean hasOffset) {
		return null;
	}

	public String getPagedString(String sql, int offset, int limit) {
		if (offset == 0) {
			return new StringBuffer(sql.length() + 8).append(sql).insert(getSqlAfterSelectInsertPoint(sql), " top " + limit).toString();
		}
		int orderByIndex = sql.toLowerCase().lastIndexOf("order by");

		if (orderByIndex <= 0) {
			throw new UnsupportedOperationException("must specify 'order by' statement to support limit operation with offset in sql server 2005");
		}

		String sqlOrderBy = sql.substring(orderByIndex + 8);
		String sqlRemoveOrderBy = sql.substring(0, orderByIndex);
		int insertPoint = getSqlAfterSelectInsertPoint(sql);
		return new StringBuilder().append(") select * from tempPagination where RowNumber between ").append(offset + 1).append(" and ").append(offset + limit).toString();
	}

	protected static int getSqlAfterSelectInsertPoint(String sql) {
		int selectIndex = sql.toLowerCase().indexOf("select");
		int selectDistinctIndex = sql.toLowerCase().indexOf("select distinct");
		return selectIndex + ((selectDistinctIndex == selectIndex) ? 15 : 6);
	}

	public boolean supportsPaged() {
		return true;
	}

	public static void main(String[] args) {
		SQLServer2005Dialect dialect = new SQLServer2005Dialect();
		String sql = "select table1.a,table2.b from table1,table2 where table1.d=table2.e order by c";
		String rs = dialect.getPagedString(sql, 1, 10);
		System.out.println("============" + rs);
	}
}